package cn.dyp.com.automaticcontrolserver.service;

import java.io.File;
import java.net.UnknownHostException;

import android.app.Service;
import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.util.Log;

import cn.dyp.com.automaticcontrolserver.AppConfig;
import cn.dyp.com.automaticcontrolserver.http.JasonSoapHttpServer;
import cn.dyp.com.automaticcontrolserver.socket.NotificationServerThread;
import cn.dyp.com.automaticcontrolserver.socket.SocketServerThread;

/**
 * Net server控制器类，其同时控制一个http服务器对象和一个socket服务器对象
 * 
 * @author ccollins
 * 
 */
public class NetServerService extends Service {
	// http服务器对象
	private JasonSoapHttpServer jsonHttpd;
	private static final String TAG = "HTTPServerService";
	// socket服务器对象
	private SocketServerThread mServerThread;
	// notification服务器对象
	private NotificationServerThread mNotifiThread;

	private final static long LOG_FILE_MAX_SIZE = 1024 * 1024;
	private String mPreLogStr = "";
	private File mLogFile;

	// 绑定Net server
	@Override
	public IBinder onBind(Intent intent) {
		Log.d(TAG, "HTTPServerService onBind()");
		return null;
	}

	// 创建Net server
	@Override
	public void onCreate() {
		Log.i(TAG, "onCreate()");
		super.onCreate();

		mLogFile = new File(AppConfig.LOG_FILE_PATH);
		if (!mLogFile.getParentFile().exists()) {
			mLogFile.getParentFile().mkdirs();
		}
		if (mLogFile.length() > LOG_FILE_MAX_SIZE) {
			mLogFile.delete();
		}
	}

	// Net server运行标记，防止重复启动
	private static boolean ifrun = false;

	// 开始启动Net server
	@SuppressWarnings("deprecation")
	@Override
	public void onStart(Intent intent, int startId) {
		Log.i(TAG, "onStart()");
		super.onStart(intent, startId);
		if (!ifrun) {
			try {
				// 创建http服务器
				jsonHttpd = new JasonSoapHttpServer(this.getLocalIpAddress(),
						AppConfig.HTTP_SERVER_PORT, getApplicationContext(),
						false);
				// 创建socket服务器
				mServerThread = new SocketServerThread(getApplicationContext(),
						AppConfig.SOCKET_SERVER_PORT, false);
				// 创建notification服务器
				mNotifiThread = new NotificationServerThread(
						getApplicationContext(), AppConfig.NOTIFI_SERVER_PORT,
						false);
			} catch (UnknownHostException e) {
				System.err.println("New JasonHttpServer instance Exception.\n");
				e.printStackTrace();
			}
			// 启动http服务
			try {
				// 启动http服务器
				jsonHttpd.start();
				System.out.println("JasonHttpd Started. ");
				// 启动socket服务器
				mServerThread.start();
				System.out.println("Socket server Started. ");
				// 启动notification服务器
				mNotifiThread.start();
				System.out.println("Notification server Started. ");
			} catch (Exception ioe) {
				System.err.println("Couldn't start JasonHttpd:\n" + ioe);
				ioe.printStackTrace();
				System.exit(-1);
			}

			ifrun = true;
		}
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.i(TAG, "onStartCommand()");
		return super.onStartCommand(intent, flags, startId);
	}

	// 注销net server
	@Override
	public void onDestroy() {
		Log.i(TAG, "onDestroy()");
		super.onDestroy();
		try {
			// 停止http服务器
			jsonHttpd.stop();
			System.out.println("JasonHttpd Stoped.");
			// 停止socket服务器
			mServerThread.stopServer();
			System.out.println("Socket Server Stoped.");
			// 停止notification服务器
			mNotifiThread.stopServer();
			System.out.println("Notification Server Stoped.");
			ifrun = false;
			Log.i(TAG, "HTTP SERVER STOPPED");
		} catch (Exception e) {
			Log.e(TAG, "ERROR can't stop JasonHttpd ", e);
		}
	}

	// 获取本地IP地址
	private String getLocalIpAddress() throws UnknownHostException {
		Log.d(TAG, "获取本地IP地址");
		WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		String IP;
		int ipAddress = wifiInfo.getIpAddress();
		IP = intToIp(ipAddress);
		return IP;
	}

	// 将ip地址转成字符串
	private String intToIp(int i) {
		return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF)
				+ "." + ((i >> 24) & 0xFF);
	}
}